/*
1. To do request Admin priviledge, add an Application Manifest file to your project in visual studio.
2. Right click your project file on the Solution Explorer, select "Add", then "New item".
There you can find Application Manifest File.
3. An app.manifest file will be added to your project.
4. In the app.manifest file, there is a <requestedExecutionLevel> element.
Modify the "level" attribute of this element as shown in the comments :
*/
/*
<!-- UAC Manifest Options
If you want to change the Windows User Account Control level replace the
requestedExecutionLevel node with one of the following.
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
Specifying requestedExecutionLevel element will disable file and registry virtualization.
Remove this element if your application requires this virtualization for backwards
compatibility.
-->
*/
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
/*
5. You can set the "level" to either "requireAdministrator" or "highestAvailable".
*/
/*
A more standard approach (but obsolete) to demand in code that the current user has Admin privileges
before running one or more guarded code is to use the PrincipalPermissionAttribute
for the guarded method of your program.
The following is an example :
*/
// NOTE PrincipalPermissionAttribute.PrincipalPermissionAttribute(SecurityAction) is obsolete
[PrincipalPermissionAttribute(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]
private static void AdministratorsCode()
{
Console.WriteLine("Administrators Only");
}
/*
Declare a usage of the System.Security.Principal and System.Security.Permissions namespaces.
Early in your program, before calling a method like AdministratorsCode(), you need to call :
*/
System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
/*
Below is a complete example code :
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Principal;
using System.Security.Permissions;
namespace ConsoleProgramRunAsAdmon
{
class Program
{
[PrincipalPermissionAttribute(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]
private static void AdministratorsCode()
{
Console.WriteLine("Administrators Only");
}
static void Main(string[] args)
{
try
{
System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
AdministratorsCode();
}
catch(Exception ex)
{
Console.WriteLine("An exception occurred : " + ex.Message);
}
Console.ReadKey();
}
}
}
// Hope that helps